//
//  SSWBStatusPicView.swift
//  shanshanlol微博
//
//  Created by 叶竞泽 on 2017/1/23.
//  Copyright © 2017年 JingZe. All rights reserved.
//

import UIKit

class SSWBStatusPicView: UIView {
    
    var viewModel: WBStatusViewModel? {
        
        didSet {
            calcViewSize()
        }
    }
    
    /// 根据式涂抹型的配图视图大小,调整显示内容
    private func calcViewSize() {
        
        // 处理高度
        heightConstraint.constant = viewModel?.picViewSize.height ?? 0
        
        // 处理宽度
        // 1.单图,根据配图视图的大小,修改subviews[0]的大小
        if viewModel?.picURLs?.count == 1{
            let v = subviews[0]
            v.frame = CGRect(x: 0, y: outterMargin, width: viewModel?.picViewSize.width ?? 0, height: viewModel?.picViewSize.height ?? 0 + 10)
        } else { // 2.多图,恢复subview[0]的大小,保证九宫格布局的完整
            let v = subviews[0]
            v.frame = CGRect(x: 0, y: outterMargin, width: itemWidth, height: itemWidth)
        }
        
    }
    
    /// 微博配图视图数组
    var urls: [SSWBStatusPic]? {
        
        didSet {
            
            // 1.隐藏所有的imageView 
            for imageView in subviews {
                imageView.isHidden = true
            }
            
            // 2.设置图像
            var index = 0
            for url in urls ?? [] {
                
                // 获得对应索引的imageView
                let imageView = subviews[index] as? UIImageView
                
                // 4张图像处理
                if index == 1 && urls?.count == 4 {
                    
                    index += 1
                }
                
                // 设置图像
                imageView?.cz_setImage(urlString: url.thumbnail_pic ?? "", placeholderImage: nil, isAvatar: false)
                // 根据扩展名设置是否显示Gif提示图像
                imageView?.subviews.first?.isHidden = ((url.thumbnail_pic ?? "") as NSString).pathExtension.lowercased() != "gif"
                // 显示图像
                imageView?.isHidden = false
                // 设置contentMode
                imageView?.contentMode = .scaleAspectFill
                imageView?.clipsToBounds = true
                
                index += 1
            }
        }
    }
    
    @IBOutlet weak var heightConstraint: NSLayoutConstraint!
    
    override func awakeFromNib() {
        
        setupUI()
    }
    
    // MARK: - 监听方法
    
    /// 监听图片点击
    @objc fileprivate func imageClick(gesture: UITapGestureRecognizer) {
        
        guard let iv = gesture.view, let picUrls = viewModel?.picURLs else { return }
        
        /// 准备通知内容
        
        // 准备index
        var index = iv.tag
        // 针对有空白图进行处理(比如4张配图的微博)
        if picUrls.count == 4 && index > 1 {
            index -= 1
        }
        
        // 准备urls
        let urls = (picUrls as NSArray).value(forKey: "largePic") as? [String]
        // 准备images
        var imagesList = [UIImage]()
        
        for imageView in subviews as! [UIImageView] {
            if !imageView.isHidden {
                if let image = imageView.image {
                    imagesList.append(image)
                }
            }
        }
        
        // 准备通知
        let userInfo = [WBShowPhotoBrowserSelectedIndexKey: index, WBShowPhotoBrowserURLsKey: urls as Any, WBShowPhotoBrowserImagesKey: imagesList]
        
        // 发送通知
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBShowPhotoBrowserNotification), object: self, userInfo: userInfo)
    }
    
}

extension SSWBStatusPicView {
    
    /// cell中所有的控件都是提前准备好,设置的时候根据数据决定是否显示,不要动态创建控件
    fileprivate func setupUI() {
        
        backgroundColor = superview?.backgroundColor
        
        /// 超出边界的内容不显示
        clipsToBounds = true
        
        let count = 3
        let rect = CGRect(x: 0, y: outterMargin, width: itemWidth, height: itemWidth)
        // 1.循环创建9个imageview
        for i in 0 ..< count * count {
            
            let imageView = UIImageView()
            
            // 设置imageView.tag
            imageView.tag = i
            
            // 行 > Y
            let row = CGFloat(i / count)
            // 列 > X
            let col = CGFloat(i % count)
            
            imageView.frame = rect.offsetBy(dx: col * (itemWidth + innerMargin), dy: row * (itemWidth + innerMargin))
            
            addSubview(imageView)
            
            // 允许imageView用户交互
            imageView.isUserInteractionEnabled = true
            // 添加imageView的点击手势识别
            let tapGesture = UITapGestureRecognizer(target: self, action: #selector(imageClick(gesture:)))
            imageView.addGestureRecognizer(tapGesture)
            // 调用添加gif图片提示的方法
            addGifView(iv: imageView)
        }
    }
    
    /// 为imageView添加Gif指示图像
    ///
    /// - Parameter iv: 要被添加指示图像的imageView
    fileprivate func addGifView(iv: UIImageView) {
        
        let gifImageView = UIImageView(image: UIImage(named: "timeline_image_gif"))
        iv.addSubview(gifImageView)
        
        // 设置gifImageView的frame
        // 取消自动布局
        gifImageView.translatesAutoresizingMaskIntoConstraints = false
        
        iv.addConstraint(NSLayoutConstraint(item: gifImageView, attribute: .left, relatedBy: .equal, toItem: iv, attribute: .left, multiplier: 1, constant: 0))
        iv.addConstraint(NSLayoutConstraint(item: gifImageView, attribute: .top, relatedBy: .equal, toItem: iv, attribute: .top, multiplier: 1, constant: 0))
    }
    
}
